package com.yyy.gui.listener;

import com.yyy.gui.pannel.BackUpPannel;
import com.yyy.gui.pannel.ConfigPanel;
import com.yyy.gui.pannel.MainPanel;
import com.yyy.service.ConfigService;
import com.yyy.util.MysqlUtil;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

/**
 * @Author：yyy
 * @Package：com.yyy.gui.listener
 * @Project：HuTuBiill
 * @name：BackupListener
 * @Date：2024/11/12 22:22
 * @Filename：BackupListener
 */
public class BackupListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        BackUpPannel p=BackUpPannel.instance;
        String mysqlPath=new ConfigService().get(ConfigService.mysqlpath);
        if(mysqlPath.length()==0){
            JOptionPane.showMessageDialog(p,"备份前请先设置好Mysql的路径");
            MainPanel.instance.workingPanel.show(ConfigPanel.instance);
            ConfigPanel.instance.tfMysqlPath.grabFocus();
            return;
        }
        JFileChooser fc=new JFileChooser();//打开文件选择器
        fc.setSelectedFile(new File("hutubill.sql"));//文件名默认设置为hutubll.sql
        fc.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".sql");
            }

            @Override
            public String getDescription() {
                return ".sql";
            }
        });

        int returnVal=fc.showSaveDialog(p);
        File file=fc.getSelectedFile();
        if(returnVal==JFileChooser.APPROVE_OPTION){
            if(!file.getName().toLowerCase().endsWith(".sql")){
                file=new File(file.getParent(),file.getName()+".sql");
            }

            try {
                MysqlUtil.backup(mysqlPath,file.getAbsolutePath());
                JOptionPane.showMessageDialog(p,"备份成功，备份文件位于：\r\n"+file.getAbsolutePath());
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(p,"备份失败\r\n错误：\r\n"+ex.getMessage());
            }
        }


    }
}
